myApp.filter('taskFilter', [function () {
    return function (tasks, filterArray) {
        var taskArr = new Array();
        var checkTaskEnable = function (filterArray1, task) {
            for (j = 1; j < filterArray1.length; j++) {
                var filter = filterArray1[j];
                if (filter.enable && task.name == filter.name) {
                    return true;
                }
                ;
            }
            ;
            return false;
        };
        for (i = 0; i < tasks.length; i++) {
            var task = tasks[i];
            if (checkTaskEnable(filterArray, task)) {
                taskArr.push(task);
            }
            ;
        }
        ;

        return taskArr;
    };
}]).filter('groupFilter', [function () {
    return function (tasks, group) {
        var taskArr = new Array();
        for (i = 0; i < tasks.length; i++) {
            var task = tasks[i];
            if (task.group == group || group == 'ALL') {
                taskArr.push(task);
            }
            ;
        }
        ;

        return taskArr;
    };
}]).filter('operationGroupsFilter', [function () {
    return function (groups) {
        var newGroups = new Array();
        newGroups.push('ALL');
        angular.forEach(groups, function (group) {
            newGroups.push(group);
        });
        return newGroups;
    };
}]).filter('versionFilter', ['$sce', function ($sce) {
    return function (taskName, versionsMap, isUseIntegration, integrationProjectList) {
        //1.分支名不存在时，返回无测试通过分支
        if (!versionsMap[taskName] || !versionsMap[taskName].editionNum) {
            return $sce.trustAsHtml("<span style='color:#d9534f;'>无测试通过版本</span>");
        } else {
            //不使用集成计划时   不校验
            if (!isUseIntegration) {
                return $sce.trustAsHtml(versionsMap[taskName].editionNum);
            }

            var rtn = null;
            //2.存在分支时，校验分支名与集成计划内工程名是否一致
            angular.forEach(integrationProjectList, function (pro) {
                if (taskName == pro.trunk_name) {
                    if (versionsMap[taskName].editionNum == pro.hand_over_edition) {
                        rtn = $sce.trustAsHtml(versionsMap[taskName].editionNum);
                        return;
                    } else {
                        rtn = $sce.trustAsHtml("<span style='color:#d9534f;'>版本与uPlan不一致(uPlan版本:" + pro.hand_over_edition
                            + ".测试通过版本:" + versionsMap[taskName].editionNum + ")</span>");
                        return;
                    }
                }
            });
            if (rtn == null) {
                return $sce.trustAsHtml(versionsMap[taskName].editionNum);
            } else {
                return rtn;
            }
        }
    };
}]).filter('branchFilter', ['$sce', function ($sce) {
    return function (taskName, versionsMap, isUseIntegration, integrationProjectList) {
        //1.分支名不存在时，返回无测试通过分支
        if (!versionsMap[taskName] || !versionsMap[taskName].projectName) {
            return $sce.trustAsHtml("<span style='color:#d9534f;'>无测试通过分支</span>");
        } else {
            //不使用集成计划时   不校验
            if (!isUseIntegration) {
                return $sce.trustAsHtml(versionsMap[taskName].projectName);
            }
            var rtn = null;
            var isInPlan = false;
            //2.存在分支时，校验分支名与集成计划内工程名是否一致
            angular.forEach(integrationProjectList, function (pro) {
                if (taskName == pro.trunk_name) {
                    isInPlan = true;
                    if (versionsMap[taskName].projectName == pro.project_name) {
                        rtn = $sce.trustAsHtml(versionsMap[taskName].projectName);
                        return;
                    } else {
                        rtn = $sce.trustAsHtml("<span style='color:#d9534f;'>分支与uPlan不一致(uPlan分支:" + pro.project_name
                            + ".测试通过分支:" + versionsMap[taskName].projectName + ")</span>");
                        return;
                    }
                }
            });
            if (rtn == null) {
                if (isInPlan) {
                    return $sce.trustAsHtml(versionsMap[taskName].projectName);
                } else {
                    return $sce.trustAsHtml("<span style='color:#d9534f;'>本期uPlan计划外工程:" + versionsMap[taskName].projectName + ")</span>");
                }
            } else {
                return rtn;
            }
        }
    };
}]);
myApp.controller('DeployController', function ($scope, $stateParams, $http, $timeout, $uibModal, Upload, $filter, $interval, ngDialog) {
    //$('.center_div').children().css("font-family","微软雅黑");
    $scope.info = {};
    $timeout(function () {
        $('.center_div,.center_div button').css('font-family', '微软雅黑');
    }, 100);
    $scope.msgQueue = new Array();
    $scope.env = {};
    //$scope.envNames=['staging','demo','production','verify'];
    $scope.envNames = new Array();
    $scope.env.name = 'staging';
    //$scope.groups=['ALL','A','B'];
    $scope.groupArray = new Array();
    $scope.filterArrays = [];
    $scope.versionsMap = {};

    $scope.userRole = getUserRole();
    $scope.canReleaseOnline = false;
    //授权时长 小时
    $scope.info.authorizeTime = '12';
    //$scope.canReleaseOnline 为true时 显示当前授权可发布的最后时间点
    $scope.releaseTime = '';

    //关联集成计划
    //系统内集成计划列表
    $scope.info.integrationList = [];
    $scope.info.isUseIntegration = false;
    $scope.info.selectIntegration = {};

    //当前周集成计划内工程列表
    $scope.info.areaIndex = 0;
    $scope.info.changeIntegration = [];
    //当前环境配置的工程 是否比uplan少
    $scope.info.isLackPro = false;
    $scope.info.lackProNames = '';

    //记录各个区域选择是否使用集成计划的信息
    $scope.info.selectInObj = {};

    //是否使用uBarrier校验
    // $scope.info.uBarrierEnv = uBarrierEnv;
    $scope.info.isUseUBarrier = false;
    $scope.info.grayGroup = 'NONE';
    $scope.info.grayDesc = null;

    //是否需要清除redis缓存
    $scope.info.isCleanRedis = true;

    $scope.canUseUBarrier = function () {
        return arrayContains(uBarrierEnv, $scope.env.name);
    };

    $scope.setNeedPrepare = function (area) {
        var key = "need-prepare-" + $scope.env.name + "-" + area.name;
        setStorage(key, area.needPrepare);
        console.log(key + ":" + area.needPrepare);
    };
    $scope.getNeedPrepare = function (area) {
        var key = "need-prepare-" + $scope.env.name + "-" + area.name;
        var value = getStorage(key);
        if (value == null || value == '') {
            area.needPrepare = false;
        } else {
            area.needPrepare = value;
        }
        console.log(key + ":" + area.needPrepare);
    };

    //获取集成计划列表,包括计划内的工程信息
    $scope.getIntegrationList = function () {
        doBeetleGet($http, $uibModal, beetle_plan_url + '/integration/getIntegrationPlanList?hasProList=true&token_id=' + getTokenId(), function (data) {
            if (data.success) {
                $scope.info.integrationList = data.data;
                if ($scope.info.integrationList.length > 0) {
                    $scope.info.selectIntegration = $scope.info.integrationList[1];
                }
            }
        });
    };
    $scope.getIntegrationList();

    //在online环境下切换区域时 查询uBarrier的切换状态
    $scope.getUBarrierStatus = function () {
        if (!$scope.canUseUBarrier()) {
            $scope.info.grayGroup = 'NONE';
            $scope.info.grayDesc = null;
            return;
        }

        if (!$scope.info.isUseUBarrier) {
            $scope.info.grayGroup = 'NONE';
            $scope.info.grayDesc = null;
            return;
        }

        var zone_code = $scope.env.areas[$scope.info.areaIndex].zone_code;
        if (zone_code == null) {
            $scope.info.grayDesc = '区域zone_code为空,请联系管理员!';
            return;
        }

        $http.get(uBarrier_url + '/zones/?env_name=' + $scope.env.name + '&zone_code=' + zone_code).success(function (data) {
            if (!data.success) {
                $scope.info.grayGroup = 'NONE';
                $scope.info.grayDesc = '获取环境切换状态异常。' + data.msg;
                return;
            }
            var list = data.data;
            if (list.length == 0) {
                openDialogAlert(ngDialog, $scope, "区域" + zone_code + "不存在");
            } else {
                if (list[0].current_status == 'GA') {
                    $scope.info.grayGroup = 'A';
                    $scope.info.grayDesc = 'A组已经切换为灰度环境，可以发版';
                } else if (list[0].current_status == 'GB') {
                    $scope.info.grayGroup = 'B';
                    $scope.info.grayDesc = 'B组已经切换为灰度环境，可以发版';
                } else if (list[0].current_status == 'GNONE') {
                    $scope.info.grayGroup = 'NONE';
                    $scope.info.grayDesc = '当前没有切换灰度环境，不可以发版';
                } else if (list[0].current_status == 'DOING') {
                    $scope.info.grayGroup = 'NONE';
                    $scope.info.grayDesc = '正在切换灰度环境，不可以发版';
                } else {
                    $scope.info.grayGroup = 'NONE';
                    $scope.info.grayDesc = '环境切换异常，不可以发版';
                }
            }
        });
    };

    $scope.link = function () {
        setStorage('integrationSet_go_back', '#/menu/deploy');
        window.location.href = '#/menu/integrationSet/' + $scope.info.selectIntegration.integration_name;
    };

    $scope.toBarrier = function () {
        window.location.href = '#/menu/barrier/';
    };

    $scope.canAuthorize = function () {
        return arrayContains($scope.userRole, 'admin') || arrayContains($scope.userRole, 'authorize');
    };

    $scope.envBtnDisable = function (envName) {
        if (envName == $scope.env.name) {
            return true;
        }
        if (envName != 'online') {
            return false;
        }
        return !$scope.canReleaseOnline;
    };

    //查询当前授权状态
    $scope.getAuthorize = function () {
        doBeetlePost($http, $uibModal, java_url + '/beetle/deploy/getAuthorize', {
            tokenId: getTokenId()
        }, function (data) {
            $scope.canReleaseOnline = false;
            $scope.releaseTime = '';
            $scope.canReleaseOnline = data.data.authorize;
            if ($scope.canReleaseOnline) {
                $scope.releaseTime = data.data.authorize_time;
            }
        });
    };
    $scope.getAuthorize();
    //授权 取消授权
    $scope.authorizeRelease = function () {
        var msg = $scope.canReleaseOnline ? "确定要取消授权发布线上环境么？" : "确定要授权发布线上环境么？";
        openDialog(ngDialog, $scope, msg, true, function (f) {
            if (!f) {
                return;
            }
            doBeetlePost($http, $uibModal, java_url + '/beetle/deploy/doAuthorize', {
                type: $scope.canReleaseOnline ? '1' : '0',
                hours: $scope.info.authorizeTime,
                tokenId: getTokenId()
            }, function (data) {
                $scope.canReleaseOnline = false;
                $scope.releaseTime = '';
                $scope.canReleaseOnline = data.data.authorize;
                if ($scope.canReleaseOnline) {
                    $scope.releaseTime = data.data.authorize_time;
                }
                if (data.code != '0') {
                    alert(data.desc);
                }
            });
        });
    };

    //终止发布
    $scope.stopDeploy = function () {
        openDialog(ngDialog, $scope, "确定要终止发布么？", true, function (f) {
            if (!f) {
                return;
            }
            doBeetlePost($http, $uibModal, java_url + '/beetle/deploy/stopDeploy', {
                envName: $scope.env.name,
                tokenId: getTokenId()
            }, function () {
            });
        });
    };

    $scope.$on("$destroy", function () {
        $interval.cancel($scope.mqTimer);
    });
    $scope.getVersionsMap = function (async) {
        if (async != false) {
            async = true;
        }
        ;
        var projectNames = new Array();
        angular.forEach($scope.env.areas, function (area) {
            angular.forEach(area.tasks, function (task) {
                projectNames.push(task.name);
            });
        });
        $.ajax({
            type: "POST",
            url: java_url + "/beetle/deploy/getPassProjectAndVersionsMap?tokenId=" + getTokenId(),
            data: JSON.stringify(projectNames),
            contentType: "application/json; charset=utf-8",
            dataType: "JSON",
            async: async,
            success: function (data) {
                if (data.code != '0') {
                    alert('error code ' + data.code + ',desc=' + data.desc);
                    return;
                }
                ;
                data = data.data.versionsMap;
                var bindData = function bindData() {
                    if (data) {
                        $scope.versionsMap = data;
                    }
                    ;
                };
                if (async) {
                    $scope.$apply(function () {
                        bindData();
                    });
                } else {
                    bindData();
                }
                ;

            },
            complete: function (xhr, status) {
            }
        });
    };
    $scope.toggle = function (panelId) {
        $('#' + panelId).collapse('toggle');
    };
    $scope.changeEnv = function (name) {
        $scope.env.name = name;
        $scope.switchEnv();
        $scope.getUBarrierStatus();
        $scope.info.isCleanRedis = true;
    };
    $scope.envBtnColor = function (name) {
        if ($scope.env.name != name) {
            return '';
        }
        return $scope.env.name;
    };
    $scope.env;
    $scope.loadEnvNames = function (async) {
        if (async != false) {
            async = true;
        }
        ;
        $.ajax({
            type: "post",
            url: java_url + "/beetle/deploy/loadEnvNames",
            data: {type: 1, tokenId: getTokenId()},
            dataType: "JSON",
            async: async,
            success: function (data) {
                if (data.code != '0') {
                    alert('error code ' + data.code + ',desc=' + data.desc);
                    return;
                }
                ;
                data = data.data.envNames;
                var bindData = function bindData() {
                    if (data) {
                        $scope.envNames = data;
                        if (data.length > 0) {
                            $scope.env.name = $scope.envNames[0];
                        }
                    }
                };
                if (async) {
                    $scope.$apply(function () {
                        bindData();
                    });
                } else {
                    bindData();
                }

            },
            complete: function (xhr, status) {
            }
        });
    };
    $scope.loadEnv = function (async) {
        if (async != false) {
            async = true;
        }
        $.ajax({
            type: "post",
            url: java_url + "/beetle/deploy/loadEvn",
            data: {type: 1, evnName: $scope.env.name, tokenId: getTokenId()},
            dataType: "JSON",
            async: async,
            success: function (data) {
                if (data.code != '0') {
                    alert('error code ' + data.code + ',desc=' + data.desc);
                    return;
                }
                data = data.data;
                var bindData = function bindData() {
                    if (data && data.list && data.list.length > 0) {
                        data = data.list[0];
                        var needNewGroupArray = false;
                        if (!$scope.env.areas || (data.areas && $scope.env.areas.length != data.areas.length)) {
                            needNewGroupArray = true;
                        }
                        $scope.env = data;
                        angular.forEach($scope.env.areas, function (area) {
                            area.status = 'running';
                            $scope.getNeedPrepare(area);
                            angular.forEach(area.tasks, function (task) {
                                task.status = [];
                            });
                        });
                        $scope.filterArraysInit();
                        if (needNewGroupArray) {
                            $scope.groupArrayInit();
                        }
                    }
                };
                if (async) {
                    $scope.$apply(function () {
                        bindData();
                    });
                } else {
                    bindData();
                }

            },
            complete: function (xhr, status) {
            }
        });
    };
    $scope.getAreaByName = function (areaName) {
        var targetArea;
        angular.forEach($scope.env.areas, function (area) {
            if (area.name == areaName) {
                targetArea = area;
                return;
            }
        });
        return targetArea;
    };
    $scope.getAreaIndexByName = function (areaName) {
        var targetArea;
        for (i = 0; i < $scope.env.areas.length; i++) {
            var area = $scope.env.areas[i];
            if (area.name == areaName) {
                targetArea = area;
                return i;
            }
        }
        return -1;
    };
    $scope.loadTaskStatus = function (async) {
        if (async != false) {
            async = true;
        }
        $.ajax({
            type: "post",
            url: java_url + "/beetle/deploy/loadTaskStatus",
            data: {type: 1, evnName: $scope.env.name, tokenId: getTokenId()},
            dataType: "JSON",
            async: async,
            success: function (data) {
                if (!data.data) {
                    return;
                }
                var versionsMap = data.data.versionsMap;
                data = data.data.status;
                var bindData = function bindData() {
                    /*var area=$scope.getAreaByName(areaName);
                     if(!area){
                     return;
                     }*/
                    $scope.versionsMap = versionsMap ? versionsMap : $scope.versionsMap;
                    angular.forEach(data, function (taskForStatus) {
                        angular.forEach($scope.env.areas, function (area) {
                            $scope.updateTaskStatus(taskForStatus, area);
                        });
                    });
                };
                if (async) {
                    $scope.$apply(function () {
                        bindData();
                    });
                } else {
                    bindData();
                }

            },
            complete: function (xhr, status) {
            }
        });
    };
    $scope.checkComplete = function () {
        if (this.task.statusMsg) {
            if (this.task.statusMsg.indexOf('完成') != -1) {
                return 'complete';
            }
            if (this.task.statusMsg == '分支版本被更新') {
                return 'warning';
            }
        }
        return '';
    };
    $scope.updateTaskStatus = function (taskForStatus, area) {
        angular.forEach(area.tasks, function (task) {
            if (task.id == taskForStatus.id) {
                if (taskForStatus.status) {
                    var statusIndex = 0;
                    angular.forEach(taskForStatus.status, function (status, i) {
                        if (status) {
                            task.status[i] = status;
                            statusIndex = i;
                            //return;
                        }
                    });
                    for (k = statusIndex + 1; k < taskForStatus.status.length; k++) {
                        task.status[k] = null;
                    }
                    //task.status=taskForStatus.status;
                }
                if (taskForStatus.statusMsg) {
                    task.statusMsg = taskForStatus.statusMsg;
                }
                if (taskForStatus.stopMsg) {
                    task.stopMsg = taskForStatus.stopMsg;
                }
                if (taskForStatus.confirm) task.confirm = taskForStatus.confirm;
            }
        });
    };
    $scope.isPause = function () {
        var isPause = false;
        if (this.task.status) {
            for (i = this.task.status.length - 1; i >= 0; i--) {
                var status = this.task.status[i];
                if (status != null && status != "" && status != undefined) {
                    if (status == 'pause') {
                        isPause = true;
                    }
                    break;
                }
            }
        }
        return this.task.confirm == 'true' || isPause ? true : false;
    };
    $scope.loadAreaStatus = function (areaName, async) {
        if (async != false) {
            async = true;
        }
        $.ajax({
            type: "post",
            url: java_url + "/beetle/deploy/loadAreaStatus",
            data: {type: 1, evnName: $scope.env.name, areaName: areaName, tokenId: getTokenId()},
            dataType: "JSON",
            async: async,
            success: function (data) {
                if (!data.data) {
                    return;
                }
                data = data.data.areaStatus;
                var bindData = function bindData() {
                    var area = $scope.getAreaByName(areaName);
                    if (!area) {
                        return;
                    }
                    $scope.updateAreaStatus(area, data);
                };
                if (async) {
                    $scope.$apply(function () {
                        bindData();
                    });
                } else {
                    bindData();
                }

            },
            complete: function (xhr, status) {
            }
        });
    };
    $scope.updateAreaStatus = function (area, data) {
        if (!area || !data) {
            return;
        }
        if (data.status) {
            area.status = data.status;
        } else {
            area.status = 'ready';
        }
        var index = $scope.getAreaIndexByName(area.name);
        if (index < 0) {
            return;
        }
        if (data.group) {
            $scope.groupArray[index] = data.group;
        }
        if (data.filterArray) {
            var newFilterArray = $scope.filterArrays[index];
            var oldFilterArray = data.filterArray;
            var allSwitch = false;
            angular.forEach(newFilterArray, function (filter1) {
                angular.forEach(oldFilterArray, function (filter2) {
                    if (filter1.name == filter2.name) {
                        filter1.enable = filter2.enable;
                    }
                });
                if (filter1.enable) {
                    allSwitch = true;
                }
            });
            newFilterArray[0].enable = allSwitch;
        }
    };
    $scope.saveAreaStatus = function (area) {
        if (!area) {
            return;
        }
        var index = $scope.getAreaIndexByName(area.name);
        $.ajax({
            type: "POST",
            url: java_url + "/beetle/deploy/saveAreaStatus/" + $scope.env.name + "/" + area.name + "?tokenId=" + getTokenId(),
            data: JSON.stringify({
                status: area.status,
                filterArray: $scope.filterArrays[index],
                group: $scope.groupArray[index]
            }),
            contentType: "application/json; charset=utf-8",
            dataType: "JSON",
            async: true,
            success: function (data) {
                if (data.code != '0') {
                    alert('error code:' + data.code + ',desc=' + data.desc);
                    return;
                }
            }
        });
    };
    $scope.filterArraysInit = function () {
        $scope.filterArrays = new Array();
        if (!$scope.env || !$scope.env.areas || $scope.env.areas.length <= 0) {
            return;
        }
        //一个区域一个filterArray
        for (i = 0; i < $scope.env.areas.length; i++) {
            var area = $scope.env.areas[i];
            var filterArray = new Array();
            filterArray.push({name: 'ALL', enable: false});
            if (area.tasks) {
                for (j = 0; j < area.tasks.length; j++) {
                    var task = area.tasks[j];
                    var flag = true;
                    //检查filterArray是否已经包含了这个任务，因为很多任务里的应用是相同的
                    for (k = 0; k < filterArray.length; k++) {
                        if (filterArray[k].name == task.name) {
                            flag = false;
                            break;
                        }
                    }
                    if (flag) {
                        filterArray.push({name: task.name, enable: false});
                    }
                }
            }
            $scope.filterArrays.push(filterArray);
        }
    };
    $scope.groupArrayInit = function () {
        $scope.groupArray = new Array();
        if (!$scope.env || !$scope.env.areas || $scope.env.areas.length <= 0) {
            return;
        }
        for (i = 0; i < $scope.env.areas.length; i++) {
            var group = 'A';
            $scope.groupArray.push(group);
        }
    };
    $scope.switchEnv = function () {
        $scope.loadEnv(false);
        angular.forEach($scope.env.areas, function (area) {
            $scope.loadAreaStatus(area.name, false);
        });
        $scope.loadTaskStatus(false);
        //$scope.getVersionsMap();
        $scope.registerMessageQueue();
        $scope.areaClick($scope.info.areaIndex);
    };

    $scope.areaClick = function (index) {
        $scope.info.areaIndex = index;
        $scope.info.isCleanRedis = true;

        var key = $scope.env.name + '_' + $scope.info.areaIndex;
        if ($scope.info.selectInObj.hasOwnProperty(key)) {
            var obj = $scope.info.selectInObj[key];
            //切换区域时 不自动根据集成计划过滤 将重置使用集成计划状态
            $scope.info.isUseIntegration = obj.isUse;
            // $scope.info.selectIntegration = obj.intG;
        } else {
            $scope.info.isUseIntegration = false;
            // $scope.info.selectIntegration = $scope.info.integrationList[1];
        }

        $scope.getUBarrierStatus();
    };

    //根据选择的集成计划，自动切换工程过滤器
    $scope.changeCheckStatusByIntegration = function (isSave) {
        var key = $scope.env.name + '_' + $scope.info.areaIndex;
        var obj = {};
        obj.isUse = $scope.info.isUseIntegration;
        // obj.intG = $scope.info.selectIntegration;
        $scope.info.selectInObj[key] = obj;

        if ($scope.info.isUseIntegration) {
            $scope.info.isLackPro = false;
            $scope.info.lackProNames = '';

            angular.forEach($scope.filterArrays[$scope.info.areaIndex], function (filter) {
                filter.enable = false;
                angular.forEach($scope.info.selectIntegration.projects, function (iPro) {
                    if (iPro.trunk_name == filter.name) {
                        filter.enable = true;
                        return;
                    }
                });
            });

            angular.forEach($scope.info.selectIntegration.projects, function (iPro) {
                var count = 0;
                angular.forEach($scope.filterArrays[$scope.info.areaIndex], function (filter) {
                    if (iPro.isOnBeetle == '1' || iPro.package_type == 'maven_jar' || iPro.trunk_name == filter.name) {
                        count = 1;
                        return;
                    }
                });
                if (count == 0) {
                    $scope.info.isLackPro = true;
                    $scope.info.lackProNames = $scope.info.lackProNames + iPro.trunk_name + ',';
                }
            });
            if ($scope.info.isLackPro) {
                $scope.info.lackProNames = $scope.info.lackProNames.substring(0, $scope.info.lackProNames.length - 1);
            }

            if ($scope.env.areas[$scope.info.areaIndex].status != 'running' && isSave) {
                $scope.saveAreaStatus($scope.env.areas[$scope.info.areaIndex]);
            }
        }
    };

    //由于angualar切换页面焦点后出现监听bug，所以页面回复焦点后重新刷新数据
    myApp.onfocus = function () {
        $scope.$apply(function () {
            $scope.loadEnv(false);
            angular.forEach($scope.env.areas, function (area) {
                $scope.loadAreaStatus(area.name, false);
            });
            $scope.loadTaskStatus(false);
        });
    };
    $scope.switchAllFilter = function (f) {
        if (f.name == 'ALL') {
            var enable = f.enable;
            var filterArray = $scope.filterArrays[this.$parent.$index];
            for (i = 1; i < filterArray.length; i++) {
                var filter = filterArray[i];
                filter.enable = enable;
            }
        } else {
            var flag = true;
            var filterArray = $scope.filterArrays[this.$parent.$index];
            for (i = 1; i < filterArray.length; i++) {
                var filter = filterArray[i];
                if (filter.enable == filterArray[0].enable) {
                    flag = false;
                    break;
                }
            }
            if (flag) {
                filterArray[0].enable = filterArray[1].enable;
            }
        }
        $scope.saveAreaStatus(this.$parent.area);
    };
    $scope.changeGroup = function () {
        $scope.info.isCleanRedis = true;
        $scope.saveAreaStatus(this.area);
    };
    $scope.isValidTasks = function (tasks, validate) {
        if (!tasks || tasks.length <= 0) {
            return false;
        }

        //使用uBarrier校验时
        if ($scope.info.isUseUBarrier) {
            if (validate != 'prepare') {
                var index = $scope.getAreaIndexByName($scope.env.areas[$scope.info.areaIndex].name);
                if ($scope.info.grayGroup == 'NONE') {
                    return false;
                } else if ($scope.info.grayGroup != $scope.groupArray[index]) {
                    return false;
                }
            }
        }

        var valid = true;
        angular.forEach(tasks, function (task) {
            var projectName = !$scope.versionsMap[task.name] || !$scope.versionsMap[task.name].projectName ? null : $scope.versionsMap[task.name].projectName;
            var editionNum = !$scope.versionsMap[task.name] || !$scope.versionsMap[task.name].editionNum ? null : $scope.versionsMap[task.name].editionNum;
            if (!projectName || !editionNum) {
                valid = false;
                return;
            }

            if (validate == 'stop' || validate == 'start') {
                if (task.type == 'ant_android') {
                    valid = false;
                    return;
                }
            }
            if (validate == 'validate' && task.type != 'tomcat') {
                valid = false;
                return;
            }
            ;
            //判断工程分支版本与集成计划要发布的是否一致  暂时不限制 只做提醒
            if ($scope.info.isUseIntegration) {
                var count = 0;
                angular.forEach($scope.info.selectIntegration.projects, function (pro) {
                    if (task.name == pro.trunk_name) {
                        count = 1;
                        if ($scope.versionsMap[task.name].projectName != pro.project_name
                            || $scope.versionsMap[task.name].editionNum != pro.hand_over_edition) {
                            valid = false;
                            return;
                        }
                    }
                });
                if (count == 0) {
                    valid = false;
                    return;
                }
            }
        });
        return valid;
    };

    $scope.openShowLogModal = function (size) {
        var task = this.task;
        var modalInstance = $uibModal.open({
            animation: true,
            templateUrl: 'TaskLogModal.html',
            controller: 'TaskLogModalCtrl',
            size: size,
            resolve: {
                task: function () {
                    return task;
                }
            }
        });
        modalInstance.result.then(function (result) {
            //alert('close');
        }, function () {
            //alert('dismiss');
        });
    };
    $scope.ready = function () {
        $scope.doTask(this.area, 'prepare');
    };
    $scope.stop = function () {
        $scope.doTask(this.area, 'stop');
    };
    $scope.backup = function () {
        $scope.doTask(this.area, 'bak');
    };
    $scope.setup = function () {
        $scope.doTask(this.area, 'install');
    };
    $scope.boot = function () {
        $scope.doTask(this.area, 'start');
    };
    $scope.validate = function () {
        $scope.doTask(this.area, 'verify');
    };
    $scope.rollback = function () {
        $scope.doTask(this.area, 'rollback');
    };
    $scope.startAll = function () {
        $scope.doTask(this.area, 'all');
    };
    $scope.doTask = function (area, btnType, async) {
        var msg = "";
        if (btnType == 'prepare') {
            msg = "准备";
        } else if (btnType == 'stop') {
            msg = "停服务";
        } else if (btnType == 'bak') {
            msg = "备份";
        } else if (btnType == 'install') {
            msg = "安装";
        } else if (btnType == 'start') {
            msg = "启动";
        } else if (btnType == 'verify') {
            msg = "校验";
        } else if (btnType == 'rollback') {
            msg = "回滚";
        } else if (btnType == 'all') {
            msg = "一键发布";
        }

        openDialog(ngDialog, $scope, "确定要执行" + msg + "么？", true, function (f) {
            if (!f) {
                return;
            }
            if (async != false) {
                async = true;
            }
            var areaIndex = $scope.getAreaIndexByName(area.name);
            var selectedTasks = $filter('groupFilter')($filter('taskFilter')(area.tasks, $scope.filterArrays[areaIndex]), $scope.groupArray[areaIndex]);
            var appIds = new Array();
            angular.forEach(selectedTasks, function (task) {
                var obj = {
                    taskId: task.id,
                    projectName: !$scope.versionsMap[task.name] || !$scope.versionsMap[task.name].projectName ? '' : $scope.versionsMap[task.name].projectName,
                    editionNum: !$scope.versionsMap[task.name] || !$scope.versionsMap[task.name].editionNum ? '' : $scope.versionsMap[task.name].editionNum
                };
                //启停服务且工程版本为空时，指定主干工程默认版本
                if (('stop' == btnType || 'start' == btnType) && (obj.projectName == '' || obj.editionNum == '')) {
                    obj.projectName = obj.projectName == '' ? task.name : obj.projectName;
                    obj.editionNum = obj.editionNum == '' ? 'default' : obj.editionNum;
                }
                appIds.push(obj);
            });
            var queueName = "release-" + $scope.env.name + "-" + area.name + "-" + "status";
            $scope.defaultStatus(selectedTasks, btnType, area.needPrepare);
            area.status = 'running';


            $.ajax({
                type: "post",
                url: java_url + '/beetle/deploy/doTask',
                data: {
                    envName: $scope.env.name,
                    areaName: area.name,
                    appIds: JSON.stringify(appIds),
                    queueName: queueName,
                    btnType: btnType,
                    isConfirm: true,
                    needPrepare: area.needPrepare,
                    tokenId: getTokenId(),
                    isCleanRedis: $scope.info.isCleanRedis
                },
                dataType: "JSON",
                async: async,
                success: function (data) {
                    if (data.code != '0') {
                        alert('error code:' + data.code + ',desc=' + data.desc);
                        if (async) {
                            $scope.$apply(function () {
                                area.status = 'ready';
                            });
                        } else {
                            area.status = 'ready';
                        }
                        return;
                    }
                    var bindData = function bindData() {
                        if (btnType == 'all') {
                            angular.forEach(selectedTasks, function (task) {
                                task.status = new Array();
                            });
                        }
                    };
                    if (async) {
                        $scope.$apply(function () {
                            bindData();
                        });
                    } else {
                        bindData();
                    }
                }
            });
        });
    };
    $scope.defaultStatus = function (selectedTasks, btnType, needPrepare) {
        var steps = ['prepare', 'stop', 'bak', 'install', 'start', 'verify'];
        var index = 0;
        if (btnType == 'all' && !needPrepare) {
            index = 1;
        } else {
            angular.forEach(steps, function (step, i) {
                if (step == btnType) {
                    index = i;
                    return;
                }
            });
        }
        angular.forEach(selectedTasks, function (task) {
            if (task.status) {
                for (k = index; k < task.status.length; k++) {
                    task.status[k] = null;
                }
            }
        });

    };
    $scope.registerMessageQueue = function () {
        $scope.msgQueue = new Array();
        var wsObj = wsObjs[0];
        wsWithReConnect(wsObj, function () {
            angular.forEach($scope.env.areas, function (area) {
                wsObj.obj.send("release-" + $scope.env.name + "-" + area.name + "-" + "status");
            });
        }, function (event) {
            $scope.msgQueue.push(event);
        });
    };
    $scope.confirmCallBack = function (cmd, async) {
        if (async != false) {
            async = true;
        }
        var task = this.task;
        var area = this.$parent.area;
        var index = $scope.getAreaIndexByName(area.name);
        $.ajax({
            type: "post",
            url: java_url + "/beetle/deploy/confirmCallBack",
            data: {taskId: task.id, type: cmd, tokenId: getTokenId()},
            dataType: "JSON",
            async: async,
            success: function (data) {
                if (data.code != '0') {
                    alert('error code:' + data.code + ',desc=' + data.desc);
                    return;
                }
                var bindData = function bindData() {
                    task.confirm = false;
                };
                if (async) {
                    $scope.$apply(function () {
                        bindData();
                    });
                } else {
                    bindData();
                }
            }
        });
    };
    $scope.test = function () {
        var getContext = function () {
            var base = document.getElementsByTagName('base')[0];
            if (base && base.href && (base.href.length > 0)) {
                base = base.href;
            } else {
                base = document.URL;
            }
            var path = base.substr(0,
                base.indexOf("/", base.indexOf("/", base.indexOf("//") + 2) + 1));

            return path.replace("http://", "ws://");
        };
        var ws = new WebSocket(getContext() + "/testmq/websocket");

        ws.onopen = function () {
            ws.send("testQueue1");
            ws.send("testQueue2");
        };

        ws.onmessage = function (event) {
            //log(event.data,'');
            var data = eval(eval('(' + event.data + ')'));
            $scope.$apply(function () {
                $scope.env.areas[0].tasks[0].status = data;
            });

        }
    };
    $scope.mqTimer = $interval(function () {
        var event = $scope.msgQueue.shift();
        if (!event) {
            return;
        }
        //var data=eval('('+event.data+')');
        var data = JSON.parse(event.data);
        //$scope.$apply(function(){
        if (data.head.type == 'areaStatus') {
            $scope.updateAreaStatus($scope.getAreaByName(data.head.areaName), data.body);
        } else if (data.head.type == 'areaTaskStatus') {
            $scope.updateTaskStatus(data.body, $scope.getAreaByName(data.head.areaName));
        } else if (data.head.type == 'tomcatStopType') {
            var area = $scope.getAreaByName(data.head.areaName);
            angular.forEach(area.tasks, function (task) {
                if (task.id == data.body.id) {
                    task.stopMsg = data.body.msg;
                    return;
                }
            });
        }
    }, 500);

    $scope.loadEnvNames(false);
    $scope.switchEnv();

    $scope.reloadJumpSSHServer = function () {
        if (!confirm("确定要初始化跳板机对象吗?初始化后会停止现有发布流程,需要重新进行发布操作!")) {
            return;
        }
        ;
        $http.post(java_url + '/beetle/jumpServer/reloadJumpSSHServer', {
            tokenId: getTokenId()
        }).success(function (data) {
            if (data.code == "0") {
                alert("初始化成功.");
            } else {
                alert(data.desc);
            }

        });
    };
    $scope.gotoUbarrier = function () {
        window.location.href = "#/menu/ubarrierAuto/";
    };

});

myApp.controller('TaskLogModalCtrl', function ($scope, $uibModalInstance, task) {
    $scope.task = task;
    $scope.log = 'this is the log.this is the log.this is the log.this is the log.this is the log.' +
        'this is the log.this is the log.this is the log.this is the log.this is the log.this is the log.' +
        'this is the log.this is the log.this is the log.this is the log.this is the log.this is the log.' +
        'this is the log.this is the log.this is the log.this is the log.this is the log.this is the log.';
    $scope.cancel = function () {
        $uibModalInstance.dismiss('cancel');
    };
});